package com.bsoft.ecommerce.service.impl;

import com.bsoft.ecommerce.account.BalanceInfo;
import com.bsoft.ecommerce.dao.EcommerceBalanceDao;
import com.bsoft.ecommerce.entity.EcommerceBalance;
import com.bsoft.ecommerce.filter.AccessContext;
import com.bsoft.ecommerce.service.IBanceService;
import com.bsoft.ecommerce.vo.LoginUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class BanceServiceImpl implements IBanceService {
    @Autowired
    private EcommerceBalanceDao ecommerceBalanceDao;

    @Override
    public BalanceInfo getCurrentUserBalanceInfo() {
        LoginUserInfo loginuserInfo = AccessContext.getLoginuserInfo();
           BalanceInfo balanceInfo = new BalanceInfo(
                   loginuserInfo.getId(),0L);
        EcommerceBalance byUserId = ecommerceBalanceDao.findByUserId(loginuserInfo.getId());
         if(null !=byUserId){
              balanceInfo.setBalance(byUserId.getBalance());
         }else {
             EcommerceBalance ecommerceBalance= new EcommerceBalance();
             ecommerceBalance.setUserId(loginuserInfo.getId());
             ecommerceBalance.setBalance(0L);
             log.info("init user balance record ",ecommerceBalanceDao.save(ecommerceBalance).getId());
         }
        return balanceInfo;
    }

    @Override
    public BalanceInfo deductBalance(BalanceInfo balanceInfo) {
        LoginUserInfo loginuserInfo = AccessContext.getLoginuserInfo();
        EcommerceBalance ecommerceBalance = ecommerceBalanceDao.findByUserId(loginuserInfo.getId());
        if(null == ecommerceBalance || ecommerceBalance.getBalance()-balanceInfo.getBalance()<0){
            throw  new RuntimeException("user balance is not");
        }
   Long sourceBalance=      ecommerceBalance.getBalance();
        ecommerceBalance.setBalance(ecommerceBalance.getBalance()-balanceInfo.getBalance());
        log.info("deduct ba;ance [{}],[{}],[{}]",ecommerceBalanceDao.save(ecommerceBalance).getId(),sourceBalance,balanceInfo.getBalance());
        return new BalanceInfo(
                ecommerceBalance.getUserId(),
                ecommerceBalance.getBalance()
        );
    }
}
